package com.kantboot.io.util;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kantboot.io.entity.CesUser;
import com.kantboot.io.exception.SessionUtilException;
import com.kantboot.io.mapper.CesSessionMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class SessionUtil {

    @Resource
    CesSessionMapper cesSessionMapper;

    public Integer deleteBySession(HttpServletRequest request){
        return cesSessionMapper.delete(new UpdateWrapper<CesSession>().eq("session_id",request.getHeader("session_id")+""));
    }

    public void setAttribute(String key, Object value, HttpServletRequest request) {
        cesSessionMapper.delete(new UpdateWrapper<CesSession>()
                                .eq("session_id",request.getHeader("session_id")+"")
                                .eq("name",key));
        cesSessionMapper.insert(
                new CesSession()
                        .setSessionId(request.getHeader("session_id"))
                        .setName(key)
                        .setVal(JSON.toJSONString(value)+""));
    }

    public String getAttribute(String key, HttpServletRequest request) {
        return
                cesSessionMapper.selectOne(
                        new QueryWrapper<CesSession>()
                                .eq("session_id", request.getHeader("session_id"))
                                .eq("name", key)
                ).getVal();

    }

    public void setCesUser(CesUser cesUser, HttpServletRequest request){
        List<CesSession> cesSessions = cesSessionMapper.selectList(new QueryWrapper<CesSession>()
                .eq("name", "cesUser").eq("session_id", request.getHeader("session_id")));

        if(cesSessions.size()>0){
            cesSessionMapper.delete(
                    new UpdateWrapper<CesSession>().eq("session_id", request.getHeader("session_id")));
        }

        cesSessionMapper.insert(
                new CesSession()
                        .setSessionId(request.getHeader("session_id"))
                        .setName("cesUser")
                        .setVal(JSON.toJSONString(cesUser)+""));
    }

    public CesUser getCesUser(HttpServletRequest request){
        try{
            return JSON.parseObject(this.getAttribute("cesUser",request)+"",CesUser.class);
        }catch (NullPointerException e){
            throw SessionUtilException.notLoginStateException();
        }
    }

}
